﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WinDocker.Common.Global;
using WinDocker.BLL;

namespace WinDocker.UC
{
    public partial class ModuleUC : UserControl
    {
        public ModuleUC()
        {
            InitializeComponent();
        }

        private string BaseDir = "";

        private List<DevSerCfgUCModel> DevSerCfgUCModelList = new List<DevSerCfgUCModel>();

        public List<DevSerCfgUCModel> DevSerCfgUCModels
        {
            get
            {
                return this.DevSerCfgUCModelList;
            }
        }

        private void ModuleUC_Load(object sender, EventArgs e)
        {
            this.BaseDir = AppDomain.CurrentDomain.BaseDirectory;
            this.DevSerCfgUCModelListInitDeal();
        }

        public void DevSerCfgUCModelListInitDeal(string cfgDirPath = "", string cfgDevSerName = "")
        {
            try
            {
                cfgDirPath = (cfgDirPath ?? "").Trim();
                cfgDevSerName = (cfgDevSerName ?? "").Trim();
                var path = $"{this.BaseDir}NDAppConfig.json";
                if (!File.Exists(path))
                {
                    return;
                }
                var json = File.ReadAllText(path, Encoding.UTF8);
                var lt = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DevSerCfgUCModel>>(json);

                //按文件夹自动增补配置项
                var bWrite = false;
                var bsDir = this.BaseDir;
                var dirPath = $@"{bsDir}Service\Deploy\KnDService";
                var dirs = Directory.GetDirectories(dirPath);
                if (dirs.Any())
                {
                    foreach (var dir in dirs)
                    {
                        if (dir.IndexOf(bsDir) != 0)
                        {
                            continue;
                        }
                        var dir2 = dir.Replace(bsDir, "");
                        if (lt.Any(p => p.DirPath == dir2))
                        {
                            continue;
                        }
                        var dirName = Path.GetFileName(Path.GetDirectoryName($@"{dir}\a.txt"));//获取最路径中的最后一个文件夹名称
                        var cfgName = "";
                        var dirNameArray = dirName.Split("_");
                        if (dirNameArray.Length >= 2)
                        {
                            cfgName = dirNameArray[1];
                            cfgName = cfgName.Replace(".exe", ".dll.config");
                        }
                        var dm = new DevSerCfgUCModel()
                        {
                            DirPath = dir2,
                            DevSerName = dirName,
                            CfgFileName = cfgName,
                            EnableFieldName = "IsEnable"
                        };
                        lt.Add(dm);
                        bWrite = true;
                    }
                }
                if (cfgDirPath != "" && cfgDevSerName != "")
                {
                    foreach (var m in lt)
                    {
                        if (m.DirPath == cfgDirPath)
                        {
                            m.DevSerName = cfgDevSerName;
                        }
                    }
                }
                if (bWrite)
                {
                    var json2 = Newtonsoft.Json.JsonConvert.SerializeObject(lt);
                    json2 = Tool.ConvertJsonString(json2);
                    File.WriteAllText(path, json2, Encoding.UTF8);
                }

                if (!lt.Any())
                {
                    return;
                }
                this.DevSerCfgUCModelList.Clear();
                this.DevSerCfgUCModelList.AddRange(lt);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "ModuleUC DevSerCfgUCModelListInitDeal Err:" + ex.Message);
            }
        }

        public void ChkCheckedShow()
        {
            try
            {
                var dealBLL = DealBLL.Init();
                int x = 0;
                int y = 0;
                var ltDevUc = new List<DevSerCfgUC>();
                foreach (var ct in this.Controls)
                {
                    if (ct is DevSerCfgUC)
                    {
                        ltDevUc.Add(ct as DevSerCfgUC);
                    }
                }
                foreach (var m in ltDevUc)
                {
                    if (this.Controls.Contains(m))
                    {
                        this.Controls.Remove(m);
                    }
                }
                foreach (var dev in this.DevSerCfgUCModelList)
                {
                    if (!dealBLL.GetDevServiceEnagble(dev.DirPath))
                    {
                        continue;
                    }
                    var uc = new DevSerCfgUC();
                    uc.DevSerCfgUCModelObj = dev;
                    uc.Parent = this;
                    uc.Location = new Point(x, y);
                    this.Width = uc.Width + 18;
                    y += (uc.Height + 0);
                    uc.Show2();
                }
                if (this.Height < y)
                {
                    this.Height = y;
                }
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "ModuleUC ChkCheckedShow Err:" + ex.Message);
            }
        }

        /// <summary>
        /// 设置所有设备服务模块的运行启用状态
        /// </summary>
        /// <param name="isRun"></param>
        public void SetAllDevSerRun(bool isRun)
        {
            try
            {
                var ltCtrol = this.Controls;
                foreach (var ct in ltCtrol)
                {
                    if (ct is DevSerCfgUC)
                    {
                        var dev = (ct as DevSerCfgUC);
                        dev.SetDevSerRun(isRun);
                    }
                }
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "ModuleUC SetAllDevSerRun Err:" + ex.Message);
            }
        }


        /// <summary>
        /// 恢复设备服务模块的运行启用状态
        /// </summary>
        /// <param name="isRun"></param>
        public void SetAllDevSerRun()
        {
            try
            {
                var ltCtrol = this.Controls;
                foreach (var ct in ltCtrol)
                {
                    if (ct is DevSerCfgUC)
                    {
                        var dev = (ct as DevSerCfgUC);
                        dev.SetDevSerRun();
                    }
                }
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "ModuleUC SetAllDevSerRun 1 Err:" + ex.Message);
            }
        }
    }

    /// <summary>
    /// 容器程序用户控件实体类
    /// </summary>
    public class DevSerCfgUCModel
    {
        /// <summary>
        /// 容器内程序的部署相对路径 如“Service\Deploy\KnDService\JtDFSer_Test.exe_0”
        /// </summary>
        public string DirPath { get; set; }
        /// <summary>
        /// 容器内程序名称
        /// </summary>
        public string DevSerName { get; set; }
        /// <summary>
        /// 配置文件名
        /// </summary>
        public string CfgFileName { get; set; }

        /// <summary>
        /// 容器内程序是否能用的配置字段名
        /// </summary>
        public string EnableFieldName { get; set; } = "";
    }
}
